<template>
  <div class="batch_conclude">
    <el-dialog
      title="处理意见"
      width="600px"
      v-dialogDrag
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      @close="close"
      customClass="mes_dialog">
      <div class="conclude_info">
        <p>周转码：<span>{{turnoverNumber}}</span></p>
        <p>发起工序：<span>{{workstageName}}</span></p>
        <p>发起人：<span>{{submitterName}}</span></p>
      </div>
      <div class="conclusion">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" v-if="dialogVisible">
          <el-form-item label="处理原因：" prop="problemProcessReasonSelect">
            <el-select v-model.trim="ruleForm.problemProcessReasonSelect" multiple @change="multipleChange" size="small"
                       placeholder="请选择处理原因">
              <el-option
                v-for="item in problemProcessReason.labels"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处理意见：" prop="remarks" class="distance">
            <el-input
              type="textarea"
              placeholder="请输入处理意见"
              rows="6"
              resize="none"
              v-model.trim="ruleForm.remarks">
            </el-input>
          </el-form-item>
          <div class="plan_number">
            <el-form-item label="投料数量：">
              <span>{{planNumber}}</span>
            </el-form-item>
            <el-form-item label="历史报废数量：" class="historyScrapQuantity"
                          v-if="historyScrapQuantity > 0">
              <span>{{historyScrapQuantity}}</span>
            </el-form-item>
          </div>
          <div class="detail_conculde">
            <el-form-item label="降级使用：" prop="degradeQuantity" class="rework">
              <el-input v-model.trim.number="ruleForm.degradeQuantity" size="small" placeholder="请输入数量"></el-input>
            </el-form-item>
            <el-form-item label="报废：" prop="scrapQuantity" class="form-item item-bottom item-group">
              <el-input v-model.trim.number="ruleForm.scrapQuantity" size="small" placeholder="请输入数量"></el-input>
            </el-form-item>
            <el-form-item label="返工返修：" prop="reworkQuantity" class="rework">
              <el-input v-model.trim.number="ruleForm.reworkQuantity" size="small" placeholder="请输入数量"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-checkbox-group v-model="ruleForm.checkedList" @change="checkItem">
                <el-checkbox label="余量自动拆分周转批次" :disabled="isDisabled"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="mes_btn">
        <el-button type="primary" @click="submitHandle">提 交</el-button>
        <el-button @click="close">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BatchConclude',
  data() {
    return {
      dialogVisible: false,
      listId: '', // 列表ID
      turnoverId: '', // 周转批次ID
      planNumber: '', // 计划数量
      turnoverNumber: '', // 周转码
      workstageName: '', // 发起工序
      submitterName: '', // 发起人
      turnoverWstageId: '', // 工序id
      historyScrapQuantity: 0, // 历史报废数量
      workstageReturn: [], // 返回工序
      problemReasonList: [],
      selectData: [],
      saveStatus: true, // 保存按钮禁用
      ruleForm: {
        problemProcessReasonSelect: [], // 处理原因
        remarks: '', // 问题描述
        workstageId: '', // 返工返修工序D
        degradeQuantity: '', // 降级使用
        scrapQuantity: '', // 报废数量
        reworkQuantity: '', // 返工返修数量
        checkedList: false,
        isNewBatchId: 'ID_BT_False', // 余量自动拆分周转批次
      },
      rules: {
        problemProcessReasonSelect: [
          {required: true, message: '请选择处理原因', trigger: 'change'}
        ],
        remarks: [
          {required: true, message: '请输入处理意见', trigger: 'blur'}
        ],
        degradeQuantity: [
          {validator: this.isPosInteger, message: '降级使用必须是正整数', trigger: 'change'},
        ],
        scrapQuantity: [
          {validator: this.isPosInteger, message: '报废数量必须是正整数', trigger: 'change'},
        ],
        reworkQuantity: [
          {validator: this.isPosInteger, message: '返工返修数量必须是正整数', trigger: 'change'},
        ],
      }
    }
  },
  computed: {
    // 处理原因
    problemProcessReason() {
      return this.$store.state.dict.problemProcessReason || []
    },
    degradeQuantity() {
      return this.ruleForm.degradeQuantity || 0
    },
    scrapQuantity() {
      return this.ruleForm.scrapQuantity || 0
    },
    reworkQuantity() {
      return this.ruleForm.reworkQuantity || 0
    },
    // 投料数量!==1时,返工返修>0时,报废+返工返修<投料数量时,余量自动拆分可勾选(是否禁用)
    isDisabled() {
      return !(this.planNumber !== 1 &&
        this.reworkQuantity > 0 &&
        (this.scrapQuantity + this.reworkQuantity + this.historyScrapQuantity < this.planNumber))
    }
  },
  methods: {
    multipleChange(list) {
      this.problemReasonList = list.reduce((pre, cur) => [...pre, {
        reasonId: cur
      }], [])
    },
    openDialog(list) {
      this.dialogVisible = true
      let data = list[0]
      this.listId = data.id
      this.ruleForm.checkedList = ''
      this.turnoverId = data.turnoverId
      this.planNumber = data.inputQuantity ? data.inputQuantity : data.turnoverProductionQuantity
      this.turnoverNumber = data.turnoverNumber
      this.workstageName = data.workstageName
      this.ruleForm.reworkstageId = data.workstageId
      this.submitterName = data.submitterName
      this.turnoverWstageId = data.turnoverWstageId
      this.getHistoryScrapQuantity()
    },
    // 获取历史报废总数
    getHistoryScrapQuantity() {
      let postData = {
        method: 'get',
        url: 'a/workstageproblemresult/workstageProblemResult/countScrapQuantity/' + this.turnoverWstageId,
        noCommit: true
      }
      this.$store.dispatch('saveData', postData).then((res) => {
        this.historyScrapQuantity = res.data || 0
      })
    },
    // 降级使用= 投料数量-报废-返工返修
    cala() {
      let bool = false
      if (this.degradeQuantity + this.scrapQuantity + this.historyScrapQuantity > this.planNumber) {
        // 降级使用+ 报废 + 历史报废
        this.tipMessage('error', '数量之和不能大于投料数量')
      } else if (this.degradeQuantity + this.reworkQuantity + this.historyScrapQuantity > this.planNumber) {
        // 降级使用+ 返工返修 + 历史报废
        this.tipMessage('error', '数量之和不能大于投料数量')
      } else if (this.scrapQuantity + this.reworkQuantity + this.historyScrapQuantity > this.planNumber) {
        // 报废+ 返工返修 + 历史报废
        this.tipMessage('error', '数量之和不能大于计划数量')
      } else if (this.planNumber - (this.scrapQuantity + this.reworkQuantity + this.historyScrapQuantity) < this.degradeQuantity) {
        // 投料数量-（报废+ 返工返修 + 历史报废）
        this.tipMessage('error', '降级使用数量不能大于投料数量-报废-返工返修-历史报废的数量之和')
      } else {
        bool = true
      }
      return bool
    },
    // 选中余量自动拆分周转批次框
    checkItem(val) {
      if (val) {
        this.ruleForm.isNewBatchId = 'ID_BT_True'
      } else {
        this.ruleForm.isNewBatchId = 'ID_BT_False'
      }
    },
    // 提交
    submitHandle() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (!this.cala()) {
            return
          }
          let postData = {
            method: 'post',
            url: 'a/workstageproblemprocess/workstageProblemProcess/problemProcessResult',
            data: {
              problemResult: {
                problemId: this.listId,
                remarks: this.ruleForm.remarks,
                reworkWorkstageId: this.ruleForm.reworkstageId,
                reworkQuantity: this.reworkQuantity,
                degradeQuantity: this.degradeQuantity,
                scrapQuantity: this.scrapQuantity,
                isNewBatchId: this.ruleForm.isNewBatchId,
                historyScrapQuantity: this.historyScrapQuantity
              },
              problemId: this.listId,
              // 处理原因的参数
              problemReasonList: this.problemReasonList,
            },
            noCommit: true
          }
          if (!this.saveStatus) return
          this.saveStatus = false
          return this.$store.dispatch('saveData', postData).then(() => {
            this.$emit('submitSuccess')
            this.tipMessage('success', '提交成功')
            this.dialogVisible = false
          }).finally(() => {
            this.saveStatus = true
          })
        }
      })
    },
    // 是否是正整数
    isPosInteger(rule, num, callback) {
      if (num && !/^[0-9]*[1-9][0-9]*$/.test(num)) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },
    // 关闭
    close() {
      this.$refs['ruleForm'].resetFields()
      this.dialogVisible = false
      this.saveStatus = true
    },
    /**
     * 提示
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .batch_conclude {
    .conclusion {
      padding: 20px;
      .el-form-item__label {
        line-height: 32px;
        padding: 0;
      }

      .el-form-item {
        margin-bottom: 20px;

        .el-form-item__content {
          line-height: 32px;
        }
      }

      .detail_conculde {
        .el-form-item {
          margin-bottom: 20px;
          &:last-child{
            margin-bottom: 0!important;
          }
        }
      }

      .plan_number .el-form-item {
        display: inline-block;
        margin-bottom: 5px;

        + .historyScrapQuantity {
          float: right;
        }
      }

      .distance {
        margin-bottom: 10px !important;
      }

      .el-select.el-select--small {
        width: 100%;
      }
    }

    .conclude_info {
      display: flex;
      align-items: center;
      justify-content: space-around;
      box-sizing: border-box;
      background-color: #ebf0f6;
      height: 30px;
      line-height: 30px;
    }

    .el-dialog__body {
      padding: 0 !important;
    }
  }
</style>
